package com.example.sentinel_demo.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.example.sentinel_demo.handler.SentinelHandler;
import com.example.sentinel_demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author JFeng
 * @Date 2024/5/9
 */

@RestController
@RequestMapping("/sentinel")
@Slf4j
public class HelloController {

    private static final String RESOURCE_NAME = "hello";
    private static final String SENTINEL_ANNOTATION_NAME = "sentinelAnnotation";

    private static final String USER_RESOURCE_NAME = "user";

    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    @RequestMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> map = new HashMap<>();
        Entry entry = null;
        try {
            // sentinel 是针对资源进行限制的，一个接口就是一个资源。
            // 通常资源名称和接口名称一样
            entry = SphU.entry(RESOURCE_NAME);

            // 配保护的逻辑代码
            LocalDateTime now = LocalDateTime.now();
            map.put("message", now);
            log.info("正常调用");
            return map;
        } catch (BlockException e) {
            // 被限流或降级了
            map.put("message", "被流控了");
            log.info("被限流了");
            return map;
//            throw new RuntimeException(e);
        } catch (Exception e) {
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(e, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return map;
    }


    /**
     * 定义流控规则
     */
    @PostConstruct
    private static void initFlowRules() {
        // 流控规则，可能是多个（针对不用接口）
        List<FlowRule> flowRules = new ArrayList<>();

        FlowRule rule = new FlowRule();
        rule.setResource(RESOURCE_NAME);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1); // QPS（每秒请求数）不能超过 1 次。

        flowRules.add(rule);


        // 注解的流控规则
        FlowRule annotationRule = new FlowRule();
        annotationRule.setResource(SENTINEL_ANNOTATION_NAME);
        annotationRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        annotationRule.setCount(1); // QPS（每秒请求数）不能超过 1 次。

        flowRules.add(annotationRule);


        // 加载配置好的规则
        FlowRuleManager.loadRules(flowRules);
    }


    /**
     * 1.引入依赖：sentinel-annotation-aspectj
     * 2.配置Bean  sentinelResourceAspect
     * 3.定义资源Value属性
     * 4.blockHandler流控方法，在本类中方法应为public，在其他类中用blockHandlerClass
     * 指定类，方法为static + public
     * 5.fallback方法中异常执行。也可以用fallbackClass指定类，fallback方法的参数需和源接口方法参数一致
     * 6.如果同时满足流控规则和异常fallback，则流控优先级更高
     * 7.exceptionsToIgnore配置fallback不处理的异常
     *
     * @return User
     */
    @SentinelResource(value = SENTINEL_ANNOTATION_NAME,
            blockHandlerClass = SentinelHandler.class,
            blockHandler = "sentinelHandler",
            fallback = "fallbackHandler",
            fallbackClass = SentinelHandler.class,
            exceptionsToIgnore = {ArithmeticException.class}
    )
    @RequestMapping("/sentinelAnnotation/{name}")
    public User sentinelAnnotation(@PathVariable String name) {
        User user = User.builder().msg("正常调用")
                .name(name)
                .age(20).build();
        int a = 0 / 0;
        return user;
    }

    /**
     * 定义降级规则
     */
    @PostConstruct
    private static void initDegradeRule() {
        List<DegradeRule> degradeRuleList = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        degradeRule.setCount(2);
        degradeRule.setMinRequestAmount(2);//触发熔断最小请求数
        degradeRule.setStatIntervalMs(60 * 1000);// 统计时长
        degradeRule.setTimeWindow(10);
        // 60秒内，请求2次，有2次异常，会熔断降级10秒，10s后的第一次调用仍然失败则继续熔断
        // 流控规则一般设在服务的调用端，降级设在消费端
        degradeRuleList.add(degradeRule);

        DegradeRuleManager.loadRules(degradeRuleList);
    }

    @RequestMapping("/degrade/{name}")
    @SentinelResource(value = DEGRADE_RESOURCE_NAME,
            entryType = EntryType.IN,
            blockHandlerClass = SentinelHandler.class,
            blockHandler = "sentinelHandlerDegrade"
    )
    public User degrade(@PathVariable String name) {
        User user = User.builder().msg("正常调用")
                .name(name)
                .age(20).build();
        if ("a".equalsIgnoreCase(name)) {
            int a = 0 / 0;
        }
        return user;
    }
}
